/*
 * Copyright (c) 2020 - present, Inspur Genersoft Co., Ltd.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.inspur.edp.cef.variableengine.core.dtm;

import com.inspur.edp.cef.api.dataType.valueObj.ICefValueObject;
import com.inspur.edp.cef.api.determination.ICefDeterminationContext;
import com.inspur.edp.cef.api.manager.ICefValueObjManager;
import com.inspur.edp.cef.designtime.api.IGspCommonField;
import com.inspur.edp.cef.entity.changeset.IChangeDetail;
import com.inspur.edp.cef.entity.entity.IValueObjData;
import com.inspur.edp.cef.spi.common.UdtManagerUtil;
import com.inspur.edp.cef.spi.determination.IDetermination;
import com.inspur.edp.lcm.metadata.api.entity.GspMetadata;
import com.inspur.edp.lcm.metadata.api.entity.MetadataCustomizationFilter;
import com.inspur.edp.lcm.metadata.api.service.MetadataRTService;
import com.inspur.edp.metadata.rtcustomization.api.CustomizationService;
import com.inspur.edp.udt.designtime.api.entity.UnifiedDataTypeDef;
import io.iec.edp.caf.commons.utils.SpringBeanUtils;

public class VariableEngineTransNestedDtmAdaptor implements IDetermination {

  private IGspCommonField gspCommonField;

  public VariableEngineTransNestedDtmAdaptor(IGspCommonField gspCommonField) {
    this.gspCommonField = gspCommonField;
  }

  @Override
  public String getName() {
    return gspCommonField.getName().concat("TransNestedDtm");
  }

  @Override
  public boolean canExecute(IChangeDetail change) {
    return true;
  }

  @Override
  public void execute(ICefDeterminationContext context, IChangeDetail change) {
    if (context.getData() == null) {
      return;
    }
    IValueObjData data = (IValueObjData) context.getData().getValue(gspCommonField.getLabelID());
    if (data == null) {
      return;
    }
    MetadataCustomizationFilter filter = new MetadataCustomizationFilter();
    filter.setMetadataId(gspCommonField.getUdtID());
    filter.setIsI18n(false);
    GspMetadata metadata = SpringBeanUtils.getBean(MetadataRTService.class).getMetadata(filter);
    UnifiedDataTypeDef unifiedDataTypeDef = (UnifiedDataTypeDef) metadata.getContent();
    ICefValueObjManager valueObjMgr = (ICefValueObjManager) UdtManagerUtil.getUdtFactory()
        .createManager(unifiedDataTypeDef.getUdtType());
    ICefValueObject valueObj = valueObjMgr.createValueObject(data);
    valueObj.beforeSaveDeterminate(com.inspur.edp.cef.entity.changeset.Util
        .getNestedPropChange(change, gspCommonField.getLabelID()));
  }
}
